package com.lin.csdn.utils;

import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

public class QrcodeUtils {
    BaseLogger baseLogger=new BaseLogger();
//转换字符串为二维码
    public String creatQrcode(String path,int blogId){
        int v =6;
        int width = 67 + 12 * (v - 1);
        int height = 67 + 12 * (v - 1);

        Qrcode x=new Qrcode();

        x.setQrcodeErrorCorrect('L');
        x.setQrcodeEncodeMode('B');//注意版本信息 N代表数字 、A代表 a-z,A-Z、B代表 其他)
        x.setQrcodeVersion(v);//版本号  1-40

        byte[] d = path.getBytes(StandardCharsets.UTF_8);//汉字转格式需要抛出异常

        //缓冲区
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);

        //绘图
        Graphics2D gs = bufferedImage.createGraphics();

        gs.setBackground(Color.WHITE);
        gs.setColor(Color.BLACK);
        gs.clearRect(0, 0, width, height);

        //偏移量
        int pixOff = 2;
        if (d.length > 0 && d.length < 120) {
            boolean[][] s = x.calQrcode(d);

            for (int i = 0; i < s.length; i++) {
                for (int j = 0; j < s.length; j++) {
                    if (s[j][i]) {
                        gs.fillRect(j * 3 + pixOff, i * 3 + pixOff, 3, 3);
                    }
                }
            }
        }
        gs.dispose();
        bufferedImage.flush();

        try {
            ImageIO.write(bufferedImage, "png", new File("G:\\WIS\\Wistudio\\web-app\\static\\picture\\share"+blogId+".png"));
        } catch (IOException e) {
            baseLogger.errorLog(String.valueOf(e));
        }
        return "..\\..\\..\\picture\\share" + blogId + ".png";
    }

}
